// pages/test/test.js
var app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		active:2,//当前页面
		list: [],
		showList: [],
		indicatorDots: false,
		vertical: false,
		autoplay: false,
		circular: false,
		interval: 2000,
		duration: 500,
		userInfo: '',
		ficationId: '',
		openId: '',
		isIphoneX: '',
		videoFlag: false,
		swiperCurrent: 0,
		searchArray: ['公司品牌', '公司名称'],
		searchIndex: 0,
		goodsId_Arr: [],
		page: 1, //当前页码
		curr: 0, //当前索引
		totalCount: 0, //数据总数
		show: false,//评论列表
		mobileShow: false,//手机号授权弹窗
		comment: null, //评论内容
		comment_list: [], //评论列表
		commPlace: '留下你的精彩评论吧',
		commDetailID: null,
		is_son : false,//是否回复
		focus: false,//是否聚焦
	},
	//输入框失去焦点
	commentBlur: function() {
		const _this = this
		_this.setData({
			commPlace: `留下你的精彩评论吧`,
			
		})
	},
	//打开评论列表
	commentDetail: function(cid) {
		const _this = this
		_this.setData({
			comment_list: [],
			is_son:false,
		})
		wx.request({
			url: app.globalData.url + '/v1/comment/show',
			method: 'GET',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				detail_id: cid
			},
			success: function(res) {
				console.log('评论详情---------', res)
				let data = res.data
				if (data.code == 0) {
					_this.setData({
						comment_list: data.data
					})
				} else {
					_this.setData({
						comment_list: []
					})
				}
			}
		})
	},
	//点击回复
	sonClick: function(e) {
		console.log("点击回复按钮------------", e) //e.currentTarget.dataset.id
		const _this = this
		_this.setData({
			commPlace: `回复：${e.currentTarget.dataset.nikname}`,
			is_son:true,
			commDetailID: e.currentTarget.dataset.id,
		})
		_this.setData({
			comment: '',
			focus: false
		}, () => {
			setTimeout(() => {
				_this.setData({
					comment: '',
					focus: true
				})
			}, 500)

		})
	},
	//关闭授权手机号弹窗
	mobileClose: function() {
		this.setData({
			mobileShow: false,
			
		})
	},
	//获取手机号
	getPhone: function(r) {
		var idx = r.currentTarget.dataset.index
		var _this = this
		wx.showToast({
			title: 'loading...',
			icon: 'loading',
			duration: 60000
		})
		if (r.detail.errMsg == 'getPhoneNumber:ok') {
			wx.checkSession({
				success: function() {
					_this.sendMobile(app.globalData.session_key, r.detail.encryptedData, r.detail
						.iv)
				},
				fail: function() {
					_this.login(r.detail.encryptedData, r.detail.iv)
				}
			})
		} else {
			wx.hideToast()
		}
	},
	login: function(encryptedData, iv, idx) {
		wx.login({
			success: function(res) {
				wx.request({
					url: app.globalData.url + '/v1/wechat/accesstoken',
					method: 'GET',
					data: {
						code: res.code
					},
					success: function(r) {
						app.globalData.session_key = r.data.data.session_key
						app.globalData.openId = r.data.data.openid
						console.log(app.globalData.session_key)
						sendMobile(app.globalData.session_key, encryptedData, iv)
					}
				})
			}
		})
	},
	sendMobile: function(session_key, encryptedData, iv) {
		var _this = this
		wx.request({
			url: app.globalData.url + '/v1/wechat/mobile',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			data: {
				encryptedData: encryptedData,
				iv: iv,
				openid: app.globalData.openId,
				session_key: session_key
			},
			success: function(res) {
				_this.setData({
					mobileShow: false
				})
				if (res.data.code == 0) {
					wx.hideToast()
					wx.showToast({
						title: '获取手机号成功！',
						icon: 'success',
						duration: 2000
					})
					_this.setData({
						show: true,
					})
				} else {
					wx.hideToast()
					wx.showToast({
						title: res.data.data.message,
						icon: 'none',
						duration: 4000
					})
				}
			}
		})
	},
	//输入的评论内容
	onChangeComment(e) {
		//console.log(e.detail);
		this.setData({
			comment: e.detail
		})
	},
	//评论
	commentSubmit() {
		console.log('评论内容-------', this.data.comment)
		const _this = this
		console.log('_this.data.commDetailID====',_this.data.commDetailID)
		if (_this.data.comment) {
			let url = null
			if(_this.data.is_son){
				url = '/v1/comment/son'
			}else{
				url = '/v1/comment/comment'
			}
			wx.request({
				url: app.globalData.url + url,
				method: 'POST',
				data: {
					detail_id: _this.data.detail_id,
					comment: _this.data.comment,
					openid: app.globalData.openId,
					comment_id:_this.data.commDetailID
				},
				success: function(r) {
					_this.setData({
						is_son:false
					})
					console.log(r);
					if (r.data.code != 0) {
						wx.showToast({
							title: r.data.msg,
							icon: 'none',
							duration: 3000
						})
					} else {
						wx.showToast({
							title: r.data.data,
							icon: 'none',
							duration: 3000
						})
						_this.setData({
							comment: null
						})
					}
				},
				fail:function(err){
					_this.setData({
						is_son:false
					})
				}
			})
		} else {
			wx.showToast({
				title: '请输入评论内容',
				icon: 'none',
				duration: 3000
			})
		}
	},
	//查看全部评论
	moreComment(e) {
		console.log('点击查看全部评论')
		wx.navigateTo({
			url: '/pages/comment/index?id=' + e.currentTarget.dataset.id
		})
	},
	//关闭评论
	onClose() {
		this.setData({
			show: false,
			comment: null
		});

	},
	//打开评论列表
	commentOpen: function(e) {
		console.log('点击打开评论列表', e)
		if (app.globalData.mobile) {
			this.setData({
				show: true,
				detail_id: e.currentTarget.dataset.cid
			})
			this.commentDetail(e.currentTarget.dataset.cid)
		} else {
			this.setData({
				mobileShow: true
			})
		}
	},
	like: function(e) {
		var _this = this;

		var temp = _this.data.list;
		const cid = _this.data.list[e.currentTarget.dataset.id].cid;


		console.log('_this.data.likeflag', temp[e.currentTarget.dataset.id].likeTag)
		if (!temp[e.currentTarget.dataset.id].likeTag) {
			temp[e.currentTarget.dataset.id].like++;
			wx.request({
				url: app.globalData.url + '/v1/goods/like',
				method: 'POST',
				data: {
					cid: cid,
					openid: app.globalData.openId
				},
				success: function(r) {
					console.log(r);
				}
			})
			temp[e.currentTarget.dataset.id].likeFormat = _this.likeFormat(temp[e.currentTarget.dataset.id].like);
			temp[e.currentTarget.dataset.id].likeTag = true;
		} else {
			temp[e.currentTarget.dataset.id].like--;
			wx.request({
				url: app.globalData.url + '/v1/goods/cancel',
				method: 'POST',
				data: {
					cid: cid,
					openid: app.globalData.openId
				},
				success: function(r) {
					console.log(r);
				}
			})
			temp[e.currentTarget.dataset.id].likeFormat = _this.likeFormat(temp[e.currentTarget.dataset.id].like);
			temp[e.currentTarget.dataset.id].likeTag = false;
		}

		this.setData({
			list: temp
		})
	},
	likeFormat(number) {
		if (number < 99999 && number > 9999) {
			return number.toString().slice(0, 1) + '.' + number.toString().slice(1, 2) + 'W';
		} else if (number < 999999 && number > 99999) {
			return number.toString().slice(0, 2) + '.' + number.toString().slice(2, 4) + 'W';
		} else if (number < 9999999 && number > 999999) {
			return number.toString().slice(0, 3) + '.' + number.toString().slice(3, 4) + 'W';
		} else if (number < 99999999 && number > 9999999) {
			return number.toString().slice(0, 4) + '.' + number.toString().slice(4, 5) + 'W';
		} else if (number < 999999999 && number > 99999999) {
			return number.toString().slice(0, 5) + '.' + number.toString().slice(5, 6) + 'W';
		} else if (number < 9999999999 && number > 999999999) {
			return number.toString().slice(0, 6) + '.' + number.toString().slice(6, 7) + 'W';
		}
		return number;
	},
	search() {
		wx.navigateTo({
			url: '/pages/search/search'
		})
	},
	//切换swiper
	swiperChange: function(e) {
		//console.log('swiper切换了------',e)
		console.log(`current===${e.detail.current},this.data.list.length===${this.data.list.length}`)
		if (e.detail.current == this.data.list.length - 2) { //当切换到倒数第二个时请求加载新列表
			if (e.detail.current > this.data.curr) {
				this.data.curr = e.detail.current
				if (Math.ceil(this.data.totalCount / 5) > this.data.page) {
					this.data.page++
					this.getList()
				} else {
					this.setData({
						circular: true
					})
				}

			}

		}
		var idx = Number(e.detail.currentItemId)
		var v
		this.setData({
			videoFlag: false,
		})
		app.globalData.ficationLOGO = this.data.list[idx].lurl
		for (let i = 0; i < this.data.list.length; i++) {
			v = wx.createVideoContext('v' + i)
			v.seek(0)
			v.pause()
		}

		if (this.data.goodsId_Arr.indexOf(this.data.list[idx].cid) === -1) {
			const temp = this.data.goodsId_Arr;
			temp.push(this.data.list[idx].cid);
			this.setData({
				goodsId_Arr: temp
			})
		}

		// wx.createVideoContext('v' + idx).play()
	},

	goodSee() {
		var _this = this;
		console.log(_this.data.goodsId_Arr);
		wx.request({
			url: app.globalData.url + '/v1/goods/see',
			method: 'POST',
			data: {
				cid: _this.data.goodsId_Arr.join(),
				openid: app.globalData.openId
			},
			success: function(r) {
				console.log(r);
				if (r.data.code == 0)
					_this.getList();
			}
		})
	},
	scrollEnd: function(e) {
		var idx = Number(e.detail.currentItemId)
		var list = this.data.list
		if (idx != 0 && idx != list.length - 1) {
			list.map(item => {
				item.isShow = false
				return item
			})
			list[idx].isShow = true
			list[idx + 1].isShow = true
			list[idx - 1].isShow = true
			this.setData({
				list: list,
			})
		}
		wx.createVideoContext('v' + idx).play()
	},
	videoClick: function(e) {
		let index = e.currentTarget.dataset.index
		let v = wx.createVideoContext('v' + index)
		if (this.data.videoFlag) {
			v.play()
			this.setData({
				videoFlag: false
			})
		} else {
			v.pause()
			this.setData({
				videoFlag: true
			})
		}
	},
	goPage: app.goPage,
	getUser: function(r) {
		console.log('id-------------------', r.currentTarget.dataset.id)
		var _this = this
		if (r.detail.errMsg == 'getUserInfo:ok') {
			app.globalData.userInfo = r.detail.userInfo
			this.setData({
				userInfo: r.detail.userInfo
			})
			wx.request({
				url: app.globalData.url + '/v1/wechat/user',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				data: {
					nikname: r.detail.userInfo.nickName,
					headimgurl: r.detail.userInfo.avatarUrl,
					openid: app.globalData.openId
				},
				success: function(res) {
					if (res.data.code == 0) {
						wx.navigateTo({
							url: '/pages/goodsDetail/goodsDetail?fid=' + r.currentTarget.dataset.id + '&up=' + r.currentTarget.dataset
								.up
						})
					} else {
						wx.showToast({
							title: '获取信息失败',
							icon: 'none',
							duration: 2000
						})
					}
				}
			})
		}
	},
	getList: function() {
		var _this = this
		if (_this.data.page == 1) {
			wx.showToast({
				icon: 'loading',
				title: 'loading...',
				duration: 60000,
				mask: true
			})
		}
		wx.request({
			url: app.globalData.url + '/v1/goods/list',
			method: 'GET',
			data: {
				size: '5',
				page: this.data.page,
				openid: app.globalData.openId
			},
			success: function(r) {
				console.log(r);
				const temp = r.data.data.items.map((item, index) => {
					if (index == 0 || index == 1) {
						item.isShow = true
					} else {
						item.isShow = false
					}
					item.gprice = Math.ceil(item.gprice)
					item.likeFormat = _this.likeFormat(item.like);
					item.likeTag = r.data.data.like.some(res => {
						return res.detail_id === item.cid;
					});

					return item
				})
				if (_this.data.page == 1) {
					app.globalData.ficationLOGO = temp[0].lurl
					_this.setData({
						goodsId_Arr: [temp[0].cid],
						list: temp,
						totalCount: r.data.data.page.totalCount
					})
				} else {
					_this.setData({
						list: _this.data.list.concat(temp)
					})
				}
				console.log('_this.data.list--------', _this.data.list)
				wx.hideToast()
			}
		})
	},
	getMobile: function() {
		var _this = this
		wx.request({
			url: app.globalData.url + '/v1/payment/show',
			method: 'GET',
			data: {
				openid: app.globalData.openId
			},
			success: function(r) {
				console.log('用户信息-----------', r)
				r = r.data
				if (r.code == 0) {
					app.globalData.mobile = r.data.user.mobile
				} else {
					wx.showToast({
						title: r.data.message,
						icon: 'none',
						duration: 2000
					})
				}
			}
		})
	},
	//切换列表
	follow: function(e) {
		const _this = this
		console.log('切换列表-------',e)//e.currentTarget.dataset.id
		if(e.currentTarget.dataset.id == 1){
			wx.showToast({
				title: '敬请期待',
				icon: 'none'
			})
			_this.setData({
				active:1
			})
		}else{
			_this.getList()
			_this.setData({
				active:2
			})
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		// if (options.data)
		//     var optionsData = JSON.parse(options.data).data;

		var _this = this
		var isIphoneX = app.globalData.isIphoneX;
		this.setData({
			isIphoneX: isIphoneX
		})
		console.log(this.data.isIphoneX)
		wx.setNavigationBarColor({
			frontColor: '#ffffff',
			backgroundColor: '#ffffff'
		})
		// 登录
		app.login().then(res => {
			console.log('登录-------------', res)
			const _this = this
			_this.setData({
				openId: res.data.openid
			})
			_this.getList()
			_this.getMobile()
		})
		/* wx.login({
		    success: res => {
		        // 发送 res.code 到后台换取 openId, sessionKey, unionId
		        wx.request({
		            url: app.globalData.url+'/v1/wechat/accesstoken',
		            method: 'get',
		            data: {
		                code: res.code
		            },
		            success: function(r) {
		                console.log(r)
		                if (r.data.code === 0) {
		                    app.globalData.session_key = r.data.data.session_key
		                    app.globalData.openId = r.data.data.openid
		                    _this.setData({
		                            openId: r.data.data.openid
		                        })
		                        // if (options.data) {
		                        //     _this.setData({
		                        //         list: optionsData.map((item, index) => {
		                        //             if (index == 0 || index == 1) {
		                        //                 item.isShow = true
		                        //             } else {
		                        //                 item.isShow = false
		                        //             }
		                        //             return item
		                        //         })
		                        //     })
		                        //     app.globalData.ficationLOGO = _this.data.list[0].lurl
		                        // } else {
		                    _this.getList()
		                        // }
		                    _this.getMobile()
		                    console.log(app.globalData.session_key)
		                    console.log(app.globalData.openId)
		                } else {
		                    wx.showToast({
		                        title: '获取信息失败',
		                        icon: 'none',
		                        duration: 2000
		                    })
		                }
		            }
		        })
		    }
		}) */
		// setTimeout(function(){
		// wx.createVideoContext('v0').play()
		// }, 1000)
		if (app.globalData.userInfo) {
			this.setData({
				userInfo: app.globalData.userInfo
			})
		} else {
			// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
			// 所以此处加入 callback 以防止这种情况
			// 给app.js 定义一个方法。
			app.userInfoReadyCallback = res => {
				app.globalData.userInfo = res.userInfo
				this.setData({
					userInfo: res.userInfo
				})
			}
		}
		// this.getList()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		for (let i = 0; i < this.data.list.length; i++) {
			let v = wx.createVideoContext('v' + i)
			v.seek(0)
			v.pause()
		}

		this.goodSee();
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		return {
			path: '/pages/index/index',
			imageUrl: '/image/sharel.png'
		}
	},
})
